import type { UnitModel, UnitType } from './types/unit-model'
// store/modules/unit/index.ts
import { defineStore } from 'pinia'

import { computed, ref } from 'vue'
import { createArrayCacheManager } from '@/utils/cache-manager'

import { asyncPriceTypes } from './api'

export const useUnitStore = defineStore('unit', () => {
  // Store 中的状态
  const priceUnits = ref<UnitModel[]>([])
  const weightUnits = ref<UnitModel[]>([])
  const priceLoading = ref(false)
  const weightLoading = ref(false)

  // 创建缓存管理器
  const priceUnitsManager = createArrayCacheManager<UnitModel>({
    fetcher: () => asyncPriceTypes('price').then(res => res.model || []),
    dataRef: priceUnits,
    loadingRef: priceLoading,
    transform: (data: any) => data,
  })

  const weightUnitsManager = createArrayCacheManager<UnitModel>({
    fetcher: () => asyncPriceTypes('weight').then(res => res.model || []),
    dataRef: weightUnits,
    loadingRef: weightLoading,
    transform: (data: any) => data,
  })

  // 获取价格单位
  const getPriceUnits = (options?: { forceRefresh?: boolean }) => {
    return priceUnitsManager.getData(options)
  }

  // 获取重量单位
  const getWeightUnits = (options?: { forceRefresh?: boolean }) => {
    return weightUnitsManager.getData(options)
  }

  // 计算属性
  const loading = computed(() => priceLoading.value || weightLoading.value)

  const getPriceUnitMapById = computed(() => {
    return new Map(priceUnits.value.map(unit => [unit.id, unit]))
  })

  const getWeightUnitMapById = computed(() => {
    return new Map(weightUnits.value.map(unit => [unit.id, unit]))
  })

  // 重置指定类型的数据
  const resetUnits = (type?: UnitType) => {
    if (!type || type === 'price') {
      priceUnits.value = []
      priceUnitsManager.reset()
    }

    if (!type || type === 'weight') {
      weightUnits.value = []
      weightUnitsManager.reset()
    }
  }

  return {
    // 状态
    priceUnits,
    weightUnits,
    loading,
    getPriceUnitMapById,
    getWeightUnitMapById,

    // 方法
    getPriceUnits,
    getWeightUnits,
    resetUnits,
  }
})
